//
//  JPPhotoPickManager.m
//  JPKY
//
//  Created by 周述坚 on 16/11/14.
//  Copyright © 2016年 Vitas. All rights reserved.
//


// 这是一个单例-- 从相册中获取图片的案例
#import "JPPhotoPickManager.h"
@interface JPPhotoPickManager ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    UIImagePickerController *_imgPickC;
    UIViewController  *_vc;
    CallBackBlock _callBackBlock;
}
@end

@implementation JPPhotoPickManager

+ (instancetype)shareInstance {
    static dispatch_once_t once;
    static JPPhotoPickManager *pickManager;
    dispatch_once(&once, ^{
        pickManager = [[JPPhotoPickManager alloc] init];
    });
    
    return pickManager;
}


- (instancetype)init {
    if([super init]){
        if(!_imgPickC){
            _imgPickC = [[UIImagePickerController alloc] init];  // 初始化 _imgPickC
        }
    }
    return self;
}

- (void)presentPicker:(PickerType)pickerType target:(UIViewController *)vc callBackBlock:(CallBackBlock)callBackBlock {
    _vc = vc;
    _callBackBlock = callBackBlock;
    if (pickerType == PickerType_Camera) {
        // 拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            _imgPickC.delegate = self;
            _imgPickC.sourceType = UIImagePickerControllerSourceTypeCamera;
            _imgPickC.allowsEditing = YES;
            _imgPickC.showsCameraControls = YES;
            UIView *view = [[UIView  alloc] init];
            view.backgroundColor = [UIColor grayColor];
            _imgPickC.cameraOverlayView = view;
            [_vc presentViewController:_imgPickC animated:YES completion:nil];
        } else {
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"" message:@"相机不可用" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alertV show];
        }
    }
    else if (pickerType == PickerType_Photo) {
        // 相册
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            _imgPickC.delegate = self;
            _imgPickC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            _imgPickC.allowsEditing = YES;
            [_vc presentViewController:_imgPickC animated:YES completion:nil];
        } else {
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"" message:@"相册不可用" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alertV show];
        }
    }
}

#pragma mark ---- UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [_vc dismissViewControllerAnimated:YES completion:^{
        // block回调
        _callBackBlock(info, NO);
    }];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [_vc dismissViewControllerAnimated:YES completion:^{
        // block回调
        _callBackBlock(nil, YES);
    }];
}

@end
